/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package damagecalculator;

import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.ToolTipManager;

/**
 *
 * @author Casal
 */
public class ButtonGrid {

    public static void createGrid(String args, JPanel frame) {
        String[][] items = XMLParser.getInfo(args); // Array with item information: 0 - Name, 1 - Tier, 2 - Price, 3 - Description
        double nrOfItems = items.length; // Number of items in array
        int cols = (int) Math.ceil(nrOfItems / 2), // Number of columns
                rows = 2, // Number of rows
                vgap = 2, // Vertical gap
                hgap = 2; // Horizontal gap
        JButton[] buttons = new ItemsButton[(int) nrOfItems]; // Array of buttons
        GridLayout layout = new GridLayout(cols, rows, vgap, hgap); // Initiate layout
        layout.preferredLayoutSize(frame); // Set preferred size
        frame.setLayout(layout); //Set layout of panel

        for (int i = 0; i < nrOfItems; i++) {
            buttons[i] = new ItemsButton("" + items[i][0] + ""); // Add button to array
            String tooltipText = "<html><b>Price:</b> " + items[i][2] + // Add information
                    "<br><b>Tier:</b> " + items[i][1],                  // to the tooltip.      
                    tooltipDescription = "<br><b>Description:</b> " + items[i][3] + "</html>"; // Add the description to a different variable. 
            int maxLength = 170; // Length of sentence to cut in half

            if (maxLength < items[i][3].length()) { // if the length of the description on tooltip is smaller than the max length.
                do {
                    maxLength++; // Look for the nearest white space after the max length token.
                } while (maxLength < items[i][3].length() && !String.valueOf(items[i][3].charAt(maxLength)).matches(" "));

                tooltipDescription = "<br><b>Description:</b> " + items[i][3].substring(0, maxLength) // Modify description on the tooltip.
                        + "<br>" + items[i][3].substring(maxLength, items[i][3].length()) + "</html>";
            }

            tooltipText += tooltipDescription; // Add the description to the tooltip, modified or not.

            buttons[i].setToolTipText(tooltipText);    //Set the tooltip
            ToolTipManager.sharedInstance().setInitialDelay(0); // Remove initial tooltip delay
            ToolTipManager.sharedInstance().setDismissDelay(60000); // Set dismiss tooltip delay to 1 minute
            frame.add(buttons[i]); // Add the button to the panel
        }
        frame.validate(); // Validate the container.
        frame.repaint(); // Refresh the container.
        frame.setVisible(true); // Set the panel visible
    }
}
